package com.liang.pcc.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.fastjson2.JSONObject;
import com.liang.pcc.chat.MessageHistoryService;
import com.liang.pcc.chat.Session;
import com.liang.pcc.chat.SessionService;
import com.liang.pcc.common.result.Result;
import com.liang.pcc.common.result.Results;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@RestController
@RequestMapping("/bai-lian")
@RequiredArgsConstructor
public class BaiLianController {

    private final SessionService sessionService;
    private final MessageHistoryService messageHistoryService;

    @SaIgnore
    @GetMapping(value = "/stream-chat", produces = "text/event-stream;charset=utf-8")
    public Flux<String> streamChat(@RequestParam(required = false) String sessionId, String userId, String msg) {
        final String[] sessionHolder = {sessionId};
        StringBuilder finalContent = new StringBuilder();
        StringBuilder reasoningContent = new StringBuilder();
        AtomicBoolean isFirstReasoning = new AtomicBoolean(true);

        try {
            // 业务逻辑处理
            if (StrUtil.isBlank(sessionHolder[0])) {
                sessionHolder[0] = sessionService.createSession(userId, "deepseek-r1");
            }

            Message userMsg = buildUserMessage(msg);
            messageHistoryService.addMessage(sessionHolder[0], userMsg);
            List<Message> fullMessages = buildFullMessages(sessionHolder[0], userMsg);
            GenerationParam param = buildGenerationParam(fullMessages);
            return Flux.from(new Generation().streamCall(param)
                    .map(chunk -> {
                        // 提取当前块内容
                        Message currentMessage = chunk.getOutput().getChoices().get(0).getMessage();
                        String reasoning = currentMessage.getReasoningContent();
                        String content = currentMessage.getContent();

                        // 累积内容
                        if (StringUtils.hasText(reasoning)) {
                            reasoningContent.append(reasoning);
                            handleReasoningOutput(reasoning, isFirstReasoning);
                        }
                        if (StringUtils.hasText(content)) {
                            finalContent.append(content);
                        }

                        // 返回给前端的格式（示例使用JSON）
                        return processGenerationResult(chunk);
                    }).doOnComplete(() -> {
                        // 5. 流结束时保存助理消息
                        Message assistantMsg = Message.builder()
                                .role(Role.ASSISTANT.getValue())
                                .content(finalContent.toString())
                                .reasoningContent(reasoningContent.toString())
                                .build();
                        messageHistoryService.addMessage(sessionHolder[0], assistantMsg);
                    })
                    .doOnError(e -> log.error("Stream error: {}", e.getMessage())));
        } catch (Exception e) {
            log.error("Initialization error: {}", e.getMessage());
            return Flux.just("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // 以下是辅助方法
    private Message buildUserMessage(String msg) {
        return Message.builder()
                .role(Role.USER.getValue())
                .content(msg)
                .build();
    }

    private List<Message> buildFullMessages(String sessionId, Message userMsg) {
        List<Message> history = messageHistoryService.getRecentMessages(sessionId, 100);
        List<Message> fullMessages = new ArrayList<>(history);
        fullMessages.add(userMsg);
        return fullMessages;
    }

    private GenerationParam buildGenerationParam(List<Message> messages) {
        return GenerationParam.builder()
                .apiKey("sk-91d178a76f2f4776ab50e30ab0e61d03")
                .model("deepseek-r1")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }

    private String processGenerationResult(GenerationResult result) {
        JSONObject response = new JSONObject();
        Message message = result.getOutput().getChoices().get(0).getMessage();

        if (StringUtils.hasText(message.getReasoningContent())) {
            response.put("type", "reasoning");
            response.put("content", message.getReasoningContent());
        }

        if (StringUtils.hasText(message.getContent())) {
            response.put("type", "content");
            response.put("content", message.getContent());
        }

        return response.toJSONString();
    }

    private void handleReasoningOutput(String reasoning, AtomicBoolean isFirst) {
        if (isFirst.compareAndSet(true, false)) {
            System.out.println("\n====================思考过程====================");
        }
        System.out.print(reasoning);
    }

    private String createErrorResponse(Throwable e) {
        JSONObject error = new JSONObject();
        error.put("type", "error");
        error.put("content", e.getMessage());
        return error.toJSONString();
    }

    /**
     * 获取会话列表
     */
    @GetMapping("/session")
    public Result<List<Session>> getSessionList(String userId) {
        List<Session> sessionList = sessionService.getSessionList(userId);
        return Results.success(sessionList);
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/session")
    public Result<Void> deleteSession(String userId, String sessionId) {
        sessionService.deleteSession(userId, sessionId);
        messageHistoryService.deleteSession(sessionId);
        return Results.success();
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/session/detail")
    public Result<List<Message>> getSessionDetail(String sessionId) {
        List<Message> messageList = messageHistoryService.getRecentMessages(sessionId, 100);
        return Results.success(messageList);
    }

    /**
     * 修改会话标题
     */
    @PutMapping("/session/title")
    public Result<Void> updateSessionTitle(String userId, String sessionId, String title) {
        sessionService.updateSessionTitle(userId, sessionId, title);
        return Results.success();
    }
}